<template>
  <div>
    <div style="margin-bottom: 20px; margin-top: 20px; text-align: center">
      <el-popconfirm
          confirm-button-text='确定'
          cancel-button-text='取消'
          icon="el-icon-info"
          icon-color="red"
          title="确定删除吗？"
          @confirm="deleteBatch"
          style="margin-right: 50px"
      >
        <el-button type="danger" icon="el-icon-remove" round style="margin-left: 15px" slot="reference">批量删除</el-button>
      </el-popconfirm>
      <el-input placeholder="请输入内容" v-model="selectValue" clearable style="width: 350px"></el-input>
      <el-button type="primary" icon="el-icon-search" round style="margin-left: 15px" @click="search">搜索</el-button>
      <el-button type="primary" icon="el-icon-refresh" round style="margin-left: 15px; margin-right: 15px" @click="reset">重置</el-button>
      <el-select v-model="partition" filterable clearable default-first-option placeholder="请选择分区">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" style="margin-left: 15px" @click="handleAdd">添加软件</el-button>
    </div>
    <el-table
        :data="tableData"
        tooltip-effect="dark"
        border
        @selection-change="handleSelectionChange"
        style="width: 100%;">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="nickName" label="软件名"></el-table-column>
      <el-table-column prop="fileVersion" label="文件版本"></el-table-column>
      <el-table-column prop="fileSize" label="文件大小"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleInfo(scope.row.id)" style="margin-right: 10px">详情</el-button>
          <el-popconfirm
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="deleteFile(scope.row.id)"
          >
            <el-button type="danger" slot="reference">删除</el-button>
          </el-popconfirm>
          <el-button type="success" @click="download(scope.row.fileUrl)" style="margin-left: 10px">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
<!--    添加软件弹窗-->
    <el-dialog
        title="添加软件"
        :visible.sync="dialogVisible"
        width="45%"
    >
      <el-form label-width="100px">
        <el-row>
          <el-col :span="7" >
            <el-form-item label="文件上传：">
              <el-upload ref="upload" :action= updateUrl :limit="1" :on-success="handleFileSuccess" :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="文件图标：">
              <el-upload
                  :action= updateIconUrl
                  :show-file-list="false"
                  :on-success="handleIconSuccess"
                  :before-upload="beforeIconUpload"
                  >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="文件大小：">
              <el-input v-model="form.fileSize" autocomplete="off" style="width: 250px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-image
                style="width: 100px; height: 100px; margin-left: 20px"
                :src="form.fileIcon"
                fit="fill">
            </el-image>
          </el-col>
          <el-col :span="12">
            <el-form-item label="软件名称:">
              <el-input v-model="form.nickName" autocomplete="off" style="width: 250px"></el-input>
            </el-form-item>
            <el-form-item label="软件分类:">
              <el-select v-model="form.types" filterable multiple clearable default-first-option placeholder="请选择分区">
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="软件版本:">
              <el-input v-model="form.fileVersion" autocomplete="off" style="width: 250px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-form-item label="软件简介:">
            <el-input v-model="form.fileProfile" type="textarea" autosize maxlength="255" show-word-limit autocomplete="off" style="width: 450px"></el-input>
          </el-form-item>
        </el-row>

      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveForm()">添 加</el-button>
      </span>
    </el-dialog>
<!--    详情弹窗-->
    <el-dialog
        title="软件详情"
        :visible.sync="dialogVisible2"
        width="45%"
    >
      <el-form label-width="100px">
        <el-row>
          <el-col :span="7" >
            <el-form-item label="文件上传：">
              <el-upload ref="upload" :action= updateUrl :limit="1" :on-success="handleFileSuccess" :file-list="fileList" :disabled="!openEdit">
                <el-button size="small" type="primary" :disabled="!openEdit">点击上传</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="文件图标：">
              <el-upload
                  :action= updateIconUrl
                  :show-file-list="false"
                  :on-success="handleIconSuccess"
                  :before-upload="beforeIconUpload"
                  :disabled="!openEdit"
              >
                <el-button size="small" type="primary" :disabled="!openEdit">点击上传</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="文件大小：">
              <el-input v-model="form.fileSize" autocomplete="off" style="width: 250px" :disabled="!openEdit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-image
                style="width: 100px; height: 100px; margin-left: 20px"
                :src="form.fileIcon"
                fit="fill">
            </el-image>
          </el-col>
          <el-col :span="12">
            <el-form-item label="软件名称:">
              <el-input v-model="form.nickName" autocomplete="off" style="width: 250px" :disabled="!openEdit"></el-input>
            </el-form-item>
            <el-form-item label="软件分类:">
              <el-select v-model="form.types" filterable multiple clearable default-first-option placeholder="请选择分区" :disabled="!openEdit">
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="软件版本:">
              <el-input v-model="form.fileVersion" autocomplete="off" style="width: 250px" :disabled="!openEdit"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-form-item label="软件简介:">
            <el-input v-model="form.fileProfile" type="textarea" autosize maxlength="255" show-word-limit autocomplete="off" style="width: 450px" :disabled="!openEdit"></el-input>
          </el-form-item>
        </el-row>

      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="handleEdit()">{{openEdit ? '关闭修改' : '开启修改'}}</el-button>
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="editForm()" :disabled="!openEdit">确认修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "AdminFileManage",
  data() {
    return {
      tableData: [],
      options: [],
      // 搜索内容
      selectValue: '',
      // 选择框选择内容
      partition: '',
      // 当前总数
      total: 0,
      // 一页大小
      pageSize: 5,
      // 当前页
      pageNum: 1,

      // 添加修改详情共用表单
      form: {},
      // 文件列表
      fileList: [],
      // 文件url
      updateUrl: this.$store.state.uploadUrl + "/admin/file/upload",
      // 文件图标url
      updateIconUrl: this.$store.state.uploadUrl + "/admin/file/upload/picture",

      // 添加页面显示
      dialogVisible: false,
      // 详情和修改页面
      dialogVisible2: false,
      // 开启修改
      openEdit: false,

      // 全选多选的数组
      multipleSelection: [],
    }
  },
  created() {
    this.loadType();
    this.loadFile();
  },
  methods: {
    // 加载类型列表，用于检索
    loadType() {
      this.request.get("/admin/file_type/simple").then(res => {
        this.options = res.data;
      });
    },
    // 加载列表文件
    loadFile() {
      this.request.get("/admin/file/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          selectValue: this.selectValue,
          partition: this.partition
        }
      }).then(res => {
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
    },
    // 获取指定文件id的类型表
    loadTypeByFileId(id) {
      this.request.get("/admin/file_type/" + id).then(res => {
        this.form.types = res.data;
      });
    },
    // 获取指定id的详细信息
    loadFileInfoById(id) {
      this.request.get("/admin/file/info/" + id).then(res => {
        this.form = res.data;
      })
    },
    // 查询
    search() {
      this.pageNum = 1;
      this.loadFile()
    },
    // 重置
    reset() {
      this.selectValue = '';
      this.partition = '';
      this.loadType();
      this.loadFile();
    },
    //修改页大小触发
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      //修改后重新加载表单
      this.loadFile();
    },
    //修改当前页触发
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      //修改后重新加载表单
      this.loadFile();
    },
    // 进入添加页面时触发
    handleAdd() {
      this.form = {};
      this.fileList = [];
      this.dialogVisible = true;
      if(this.$refs.upload !== undefined) {
        this.$refs.upload.clearFiles();
      }
    },
    // 进入详情页面时触发
    handleInfo(id) {
      this.openEdit = false;
      this.form = {};
      this.fileList = [];
      this.dialogVisible2 = true;
      if(this.$refs.upload !== undefined) {
        this.$refs.upload.clearFiles();
      }
      this.loadFileInfoById(id);
      this.loadTypeByFileId(id);
    },
    // 根据id删除一条文件信息
    deleteFile(id) {
      this.request.delete("/admin/file/" + id).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg);
          this.loadFile();
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    // 开启和关闭修改都会触发
    handleEdit() {
      // 切换可否修改状态
      this.openEdit = !this.openEdit;
      this.fileList = [];
      if(this.$refs.upload !== undefined) {
        this.$refs.upload.clearFiles();
      }
      this.loadFileInfoById(this.form.id);
      this.loadTypeByFileId(this.form.id);
    },
    // 文件上传成功触发
    handleFileSuccess(res) {
      this.$set(this.form, "fileUrl", res)
    },
    // 图标上传成功时触发
    handleIconSuccess(res) {
      this.$set(this.form, "fileIcon", res)
    },
    // 图标上传前触发
    beforeIconUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isJPG && isLt5M;
    },
    // 添加文件信息
    saveForm() {
      this.request.post("/admin/file", this.form).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg);
          this.form = {};
          this.fileList = [];
          if(this.$refs.upload !== undefined) {
            this.$refs.upload.clearFiles();
          }
          this.loadFile()
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    // 修改文件信息
    editForm() {
      this.request.put("/admin/file", this.form).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg);
          this.loadFile();
        }
      });
    },
    // 下载单个文件
    download(url) {
      window.open(url);
    },
    //获取多选结果
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 批量删除
    deleteBatch() {
      //multipleSelection为多选的数组
      if(this.multipleSelection.length == 0) {
        this.$message.warning("未选择任何选项");
        return;
      }
      //map函数将对象按照要求转化为学号数组
      let ids = this.multipleSelection.map(v => v.id); // [{}, {}, {}] => [1, 2, 3]
      this.request.post("/admin/file/batch", ids).then(res => {
        if(res.code == 200) {
          this.$message.success(res.msg);
          this.loadFile();
        }else {
          this.$message.error("服务器异常！");
        }
      });
    },
  }
}
</script>

<style scoped>

</style>
